from socket import *
from select import select
import re,sys
import pymysql

class MySql:
    def __init__(self,user=None,passwd=None,word=None):
        self.user = user
        self.passwd = passwd
        self.word = word
        self.__db = self.__connect()
        self.__cur = self.__db.cursor()

    # 这里写死了，可以在构造函数中提供接口 关键字传参IP 端口 用户 密码 和数据库
    def __connect(self):
        db = pymysql.connect(host='localhost',port=3306,user='root',passwd='123.com',
                database='dict_user',charset='utf8')
        return db

    def close(self):
        self.__cur.close()
        self.__db.close()

    def login(self):
        sql = 'select * from user where uname = %s and passwd = %s'
        self.__cur.execute(sql,[self.user, self.passwd])
        one_row = self.__cur.fetchone()
        if one_row:
            return one_row
        else:
            return None

    def register(self):
        # 注册过
        if self.login():
            return False
        # 未注册过
        sql = 'insert into user (uname,passwd) values (%s,%s)'
        try:
            self.__cur.execute(sql,[self.user, self.passwd])
            self.__db.commit()
            return True
        # 捕获异常
        except Exception as e:
            self.__db.rollback()
            print(e)
            return False


    def work(self):
        sql = 'select means from word where word = %s'
        self.__cur.execute(sql,[self.word])
        one_row = self.__cur.fetchone()
        return one_row

# 客户端登录
def login(connfd):
    connfd.send(b'OK')
    # 接收用户名密码
    data = connfd.recv(1024).decode()
    if not data:
        return
    user_name = re.findall(r'^\S+',data)
    passwd = re.findall(r'\S+$',data)
    # 拿到用户名密码
    #print("name:%s, passwd:%s"%(user_name,passwd))
    sql = MySql(user_name,passwd)
    if not sql.login():
        connfd.send(b'Login error,please register first')
    else:
        connfd.send(b'login successfully')
        while True:
            word = connfd.recv(64).decode()
            if word == 'E':
                sql.close()
                return
                
            m = MySql(word=word)
            row = m.work()
            if not row:
                connfd.send(b'not find this word')
            elif row:
                for item in row:
                    connfd.send(item.encode())


# 客户端注册
def registor(connfd):
    connfd.send(b'YES')
    # 接收用户名密码
    data = connfd.recv(1024).decode()
    if not data:
        return
    user_name = re.findall(r'^\S+',data)
    passwd = re.findall(r'\S+$',data)
    sql = MySql(user_name, passwd)
    if not sql.register():
        connfd.send(b'username all really registered')
    else:
        connfd.send(b'register successfully')


def sock_server():
    sockfd = socket()
    sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,True)
    sockfd.bind(('0.0.0.0',8888))
    sockfd.listen(5)
    print("[*] Listening port 8888 ...")
    rlist = [sockfd]
    wlist = []
    xlist = []
    while True:
        rs,ws,xs = select(rlist,wlist,xlist)
        for r in rs:
            if r is sockfd:
                connfd,addr = sockfd.accept()
                print("Connect from:", addr)
                rlist.append(connfd)
            else:
                data = r.recv(32).decode()
                if data.strip() == 'L':
                    login(r) # 登录
                    print('Connect exit')

                elif data.strip() == 'R':
                    registor(r) # 注册

                else:
                    r.close()
                    rlist.remove(r)
                    
def main():
    try:
        sock_server()
    except KeyboardInterrupt:
        sys.exit(" Thank for use")


if __name__ == "__main__":
    main()



